package com.zengqingfa.springboot.es.util;

import com.zengqingfa.springboot.es.entity.Content;
import lombok.val;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @fileName: HtmlParseUtil
 * @author: zengqf3
 * @date: 2020-7-3 21:08
 * @description:
 */
@Component
public class HtmlParseUtil {

    private HtmlParseUtil(){}


    public static void main(String[] args) throws Exception {
        new HtmlParseUtil().parseJd("心理学").forEach(System.out::println);

    }


    /**
     * 解析jd
     *
     * @param keywords
     * @return
     * @throws Exception
     */
    public List<Content> parseJd(String keywords) throws Exception {
        //获取数据 https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword=" + keywords;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        //获取所有的li标签
        Elements elements = element.getElementsByTag("li");
        List<Content> contents = new ArrayList<>();
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            String shop = el.getElementsByClass("p-shop").eq(0).tagName("a").text();
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setShop(shop);
            content.setTitle(title);
            contents.add(content);
        }
        return contents;
    }
}
